package cn.chenhuanming.chuanzhi.util.authority;


import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/1/5.
 */
public class AuthorityTool {

    /**
     * @function 检查是否已登录，已登录返回true，否则返回false
     * @return true/false
     */
    public static boolean isAuthenticated(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication==null||authentication.getPrincipal().equals("anonymousUser")||!authentication.isAuthenticated())
            return false;
        else
            return true;
    }

    /**
     * 获取当前用户的所有权限
     * @return
     */
    public static List<String> authorities(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        List<String> authorities = new ArrayList<>();
        authentication.getAuthorities().forEach(a->authorities.add(a.getAuthority()));
        return authorities;
    }
    /**
     * @function 获取当前用户的用户名。
     * @return 用户的用户名
     *
     */
    public static String getPrincipal(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        return user.getUsername();
    }
}
